#!/usr/bin/env python2

import platform
import errno
import re
import os
import string
import time

from utils import Exp, _dmsg, _dwarn, _exec_pipe, _exec_system
from disk.Iface import DISK_Iface

class SPDK(DISK_Iface):
    def get_disk_pool(self, dev):
        return dev.split('_')[1]

    def get_disk_info(self, dev):
        return {"type":"SPDK", "interface":"PCI", "media_type": "NVMe"}

    def show_disk_info(self, dev, dev_info):
        if dev_info['media_type'] == dev_info['type']:
            media_type = dev_info['media_type']
        else:
            media_type = dev_info['media_type'] + "(" + dev_info['type'] + ")"
        return "  %-6s %-6s %-6s" %(dev, media_type, dev_info['interface'])

    def get_disk_real(self, dev):
        return dev.split('_')[-1]

    def get_disk_target(self, dev, disk_num, pool):
        target = "/etc/pci_" + pool + '_disk' + str(disk_num) + '_' + dev
        _exec_system("touch " + target)
        return target

    def get_new_disk(self, used_disk):
        new_disk = []
        all_devs = self.disktool.get_all_spdk()
        for dev in all_devs:
            used = False
            for item in used_disk:
                if dev in used_disk[item].keys():
                    used = True
                for disk in used_disk[item]:
                    if dev in used_disk[item][disk]:
                        used = True
            if not used:
                new_disk.append(dev)
                if '__newdev__' not in used_disk:
                    used_disk['__newdev__'] = {}
                    used_disk['__newdev__'][dev] = self.disk.get_disk_real(dev)
        return new_disk

    def get_new_info(self, dev):
        return self.get_disk_info(dev)

    def show_new_disk(self, dev, dev_info):
        return self.show_disk_info(dev, dev_info)

    def get_all_disk(self, used_disk):
        return self.get_new_disk(used_disk)

    def disk_load_valid(self, dev, clusteruuid, hostname):
        d = {}
        for path in os.listdir('/etc'):
            if path.startswith('pci_'):
                if path.endswith(dev):
                    s = path.split('_')
                    d['cluster'] = clusteruuid
                    d['node'] = hostname
                    d['type'] = 'data'
                    d['pool'] = s[1]
                    d['disk'] = s[2][4:]
                    return d
        return None

    def disk_info_valid(self, dev, buff):
        return True
